/**
 * @file test_bemfaclient_protocol.cpp
 * @brief 巴法云协议完整性测试
 *
 * 测试所有巴法云TCP协议功能，验证优化后的效果
 */

#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include "../src/io/bemfaclient.h"
#include "../src/utils/logger.h"
#include "../src/utils/config.h"

void testBasicCommands(BemfaClient *client);
// void testAdvancedCommands(BemfaClient *client); // Removed: functions not in production code
void testErrorHandling(BemfaClient *client);

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // 初始化日志
    QString logPath = "C:/Users/86188/Desktop/ModbusPro/QModbusPowerCloud/logs/test_protocol.log";
    Logger::instance()->initialize(logPath);
    Logger::instance()->info("Test", "========== 巴法云协议测试程序启动 ==========");

    // 加载配置
    QString configPath = "C:/Users/86188/Desktop/ModbusPro/QModbusPowerCloud/config/settings.ini";
    Config *config = Config::instance();
    if (!config->initialize(configPath))
    {
        qCritical() << "配置文件加载失败！";
        return -1;
    }

    if (!config->isBemfaEnabled())
    {
        qWarning() << "巴法云未启用，请在配置文件中设置Bemfa/Enabled=true";
        return 0;
    }

    // 创建客户端
    BemfaClient *client = new BemfaClient();

    QString host = config->getBemfaHost();
    int port = config->getBemfaPort();
    QString uid = config->getBemfaUid();

    if (!client->initialize(host, port, uid))
    {
        qCritical() << "客户端初始化失败！";
        return -1;
    }

    qInfo() << "\n========== 测试环境 ==========";
    qInfo() << "服务器：" << host << ":" << port;
    qInfo() << "用户UID：" << uid;
    qInfo() << "测试主题：powercloud001, powercloud002, powercloud003";

    // 连接信号
    QObject::connect(client, &BemfaClient::connectionEstablished, [client]()
                     {
        qInfo() << "\n✅ 连接成功！";
        qInfo() << "等待3秒后开始测试...";
        
        // 延迟开始测试，确保连接稳定
        QTimer::singleShot(3000, [client]() {
            testBasicCommands(client);
        }); });

    QObject::connect(client, &BemfaClient::connectionLost, []()
                     { qWarning() << "\n❌ 连接断开！"; });

    QObject::connect(client, &BemfaClient::subscribeSucceeded, [](const QString &topics)
                     { qInfo() << "✅ 订阅成功：" << topics; });

    QObject::connect(client, &BemfaClient::publishSucceeded, [](const QString &topic)
                     { qInfo() << "✅ 发布成功：" << topic; });

    QObject::connect(client, &BemfaClient::messageReceived,
                     [](const QString &topic, const QString &message)
                     {
                         qInfo() << "📨 收到消息 [" << topic << "]：" << message;
                     });

    QObject::connect(client, &BemfaClient::errorOccurred, [](const QString &error)
                     { qWarning() << "❌ 错误：" << error; });

    // 连接服务器
    qInfo() << "\n正在连接到巴法云服务器...";
    client->connectToServer();

    // 30秒后退出
    QTimer::singleShot(30000, [&app]()
                       {
        qInfo() << "\n========== 测试完成，程序退出 ==========";
        app.quit(); });

    int ret = app.exec();

    delete client;
    return ret;
}

/**
 * @brief 测试基本命令（cmd=1, cmd=2, 心跳）
 */
void testBasicCommands(BemfaClient *client)
{
    qInfo() << "\n========================================";
    qInfo() << "测试1：基本订阅和发布功能";
    qInfo() << "========================================";

    // Test 1.1: 订阅单个主题
    QTimer::singleShot(0, [client]()
                       {
        qInfo() << "\n[Test 1.1] 订阅单个主题";
        client->subscribe("powercloud001"); });

    // Test 1.2: 发布文本消息
    QTimer::singleShot(1000, [client]()
                       {
        qInfo() << "\n[Test 1.2] 发布文本消息";
        client->publish("powercloud001", "test_message"); });

    // Test 1.3: 发布JSON消息
    QTimer::singleShot(2000, [client]()
                       {
        qInfo() << "\n[Test 1.3] 发布JSON消息";
        QJsonObject json;
        json["type"] = "test";
        json["value"] = 123;
        json["status"] = "ok";
        client->publishJson("powercloud001", json); });

    // Test 1.4: 使用/up后缀（只更新云端，不推送）
    QTimer::singleShot(3000, [client]()
                       {
        qInfo() << "\n[Test 1.4] 使用/up后缀上传数据";
        QJsonObject json;
        json["id"] = 1;
        json["data"] = "upload_only";
        client->publishJson("powercloud001/up", json); });

    // 延迟测试错误处理（跳过高级命令测试）
    QTimer::singleShot(5000, [client]()
                       { testErrorHandling(client); });
}

/**
 * @brief 测试高级命令（cmd=3, cmd=7, cmd=9）
 * COMMENTED OUT: These functions (subscribeWithHistory, getHistoryMessage, getServerTime)
 * have been removed from BemfaClient as they are not used in production code.
 */
/*
void testAdvancedCommands(BemfaClient *client)
{
    qInfo() << "\n========================================";
    qInfo() << "测试2：高级协议功能";
    qInfo() << "========================================";

    // Test 2.1: 订阅并获取历史消息（cmd=3）
    QTimer::singleShot(0, [client]()
                       {
        qInfo() << "\n[Test 2.1] 订阅主题并获取历史消息（cmd=3）";
        client->subscribeWithHistory("powercloud002"); });

    // Test 2.2: 获取历史消息（cmd=9）
    QTimer::singleShot(2000, [client]()
                       {
        qInfo() << "\n[Test 2.2] 获取主题历史消息（cmd=9）";
        client->getHistoryMessage("powercloud001"); });

    // Test 2.3: 获取服务器时间 - 日期+时间（cmd=7, type=1）
    QTimer::singleShot(4000, [client]()
                       {
        qInfo() << "\n[Test 2.3] 获取服务器时间（日期+时间）";
        client->getServerTime(1); });

    // Test 2.4: 获取服务器时间 - 仅时间（cmd=7, type=2）
    QTimer::singleShot(6000, [client]()
                       {
        qInfo() << "\n[Test 2.4] 获取服务器时间（仅时间）";
        client->getServerTime(2); });

    // Test 2.5: 获取服务器时间 - 时间戳（cmd=7, type=3）
    QTimer::singleShot(8000, [client]()
                       {
        qInfo() << "\n[Test 2.5] 获取服务器时间（时间戳）";
        client->getServerTime(3); });

    // 延迟测试错误处理
    QTimer::singleShot(10000, [client]()
                       { testErrorHandling(client); });
}
*/

/**
 * @brief 测试错误处理和边界情况
 */
void testErrorHandling(BemfaClient *client)
{
    qInfo() << "\n========================================";
    qInfo() << "测试3：错误处理和边界情况";
    qInfo() << "========================================";

    // Test 3.1: 发布长消息
    QTimer::singleShot(0, [client]()
                       {
        qInfo() << "\n[Test 3.1] 发布长消息（测试截断显示）";
        QString longMsg = "这是一条很长的消息用于测试日志截断功能" + QString("X").repeated(100);
        client->publish("powercloud001", longMsg); });

    // Test 3.2: 发布空消息
    QTimer::singleShot(2000, [client]()
                       {
        qInfo() << "\n[Test 3.2] 发布空消息";
        client->publish("powercloud001", ""); });

    // Test 3.3: 测试多个快速发布
    QTimer::singleShot(4000, [client]()
                       {
        qInfo() << "\n[Test 3.3] 连续快速发布（测试消息关联）";
        client->publish("powercloud001", "msg1");
        client->publish("powercloud002", "msg2");
        client->publish("powercloud003", "msg3"); });

    // Test 3.4: 订阅多个主题
    QTimer::singleShot(6000, [client]()
                       {
        qInfo() << "\n[Test 3.4] 订阅多个主题（测试主题列表回显）";
        client->subscribe("powercloud001,powercloud002,powercloud003"); });

    qInfo() << "\n所有测试已排队，等待执行完成...";
}
